package com.yj.auto.utils;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jfinal.core.Controller;

public class ModelUtil {
	/**
	 * 前端以 model[XX].id的方式提交Model数组，获取所有Key，对应前端input name="user[XX].id"
	 * 
	 * @param names
	 *            表单提交的所有
	 * @param modelName
	 *            model名称，如上面的user
	 * @return
	 */
	public static Set<String> getModelKeys(Enumeration<String> names, String modelName) {
		String reg = "^" + modelName + "\\[.+?\\]\\.{1}.+";
		Pattern pattern = Pattern.compile(reg);
		Set<String> keys = new HashSet<String>();
		while (names.hasMoreElements()) {
			String key = names.nextElement();
			//System.out.println(key);
			Matcher matcher = pattern.matcher(key);
			if (matcher.find()) {
				keys.add(key.substring(0, key.indexOf(".")));
			}
		}
		return keys;
	}

	public static <T> List<T> getBeans(Controller controller, Class<T> modelCls, String modelName) {
		List<T> list = new ArrayList<T>();
		Set<String> keys = getModelKeys(controller.getParaNames(), modelName);
		for (String s : keys) {
			T model = controller.getBean(modelCls, s);
			list.add(model);
		}
		return list;
	}

	public static void main(String[] args) {
		String prefix = "model";
		String s = "model[abc].1";
		String reg = "^" + prefix + "\\[.+?\\]\\.{1}.+";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(s);
		if (matcher.find()) {
			System.out.println(s.substring(0, s.indexOf(".")));
		}
	}
}
